<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace User\Controller;

use User\Model\Entity\Settings;
use User\Model\Entity\User;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class UserController extends AbstractActionController {
	/**
     * @var UserModel
     */
	protected $userModel;
	
	/**
     * @var CountryModel
     */
	protected $countryModel;
	
	public function getUserModel() {
		if(!$this->userModel) {
			$sm = $this->getServiceLocator();
			$this->userModel = $sm->get('User\Model\UserModel');
		}
		return $this->userModel;
	}
	
	public function getCountryModel() {
		if(!$this->countryModel) {
			$sm = $this->getServiceLocator();
			$this->countryModel = $sm->get('Application\Model\CountryModel');
		}
		return $this->countryModel;
	}

	/**
     * User page
     */
	public function indexAction() {
		if(!$this->userAuthenticationPlugin()->hasIdentity()) {
			return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getLoginRoute());
        }
        return new ViewModel();
	}
	
	/**
     * Login form
     */
	public function loginAction() {
		if($this->userAuthenticationPlugin()->hasIdentity()) {
            return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getRedirectRouteLogin());
        }
        
		$form = new \User\Form\LoginForm();
		$user = new User();
		$form->bind($user);
		$request = $this->getRequest();

		if($request->isPost()) {
			$data = $request->getPost();
			$form->setData($data);
			
			if($form->isValid()) {
				$this->userAuthenticationPlugin()->getAuthService()->clearIdentity();
				$request->setPost(new \Zend\Stdlib\Parameters(array(
					'user' => $user,
					'rememberme' => $data['user']['rememberme'],
				)));
		        return $this->forward()->dispatch('User\Controller\User', array('action' => 'authenticate'));
			}
		}

		return new ViewModel(array(
            'form' => $form,
		));
	}
	
	/**
     * Logout and clear the identity
     */
    public function logoutAction() {
        $this->userAuthenticationPlugin()->getAuthService()->getStorage()->forgetMe();
        $this->userAuthenticationPlugin()->getAuthService()->clearIdentity();
        return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getRedirectRouteLogout());
    }
    
    /**
     * General-purpose authentication action
     */
	public function authenticateAction() {
		$request = $this->getRequest();
		
		if($request->isPost()) {
			$user = $request->getPost('user');
			$authService = $this->userAuthenticationPlugin()->getAuthService();
			$authService->getAdapter()
						->setIdentity($user->getEmail())
						->setCredential($user->getPassword());
			
			$auth = $authService->authenticate();
			if($auth->isValid()) {
				$storage = $authService->getStorage();
				$rememberMe = (bool) $request->getPost('rememberme');
				if($rememberMe) {
					$storage->setRememberMe(1);
				}
				$storage->write($authService->getAdapter()->getResultRowObject(null, 'password'));
				return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getRedirectRouteLogin());
			}
		}
		return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getLoginRoute());
	}
	
	public function registerAction() {
		$registrationEnable = $this->userModuleSettingsPlugin()->getRegistrationEnable();
		// if registration is disabled
        if(!$registrationEnable) {
            return array(
            	'enableRegistration' => false
            );
        }
        
		$form = new \User\Form\RegisterForm($this->userModuleSettingsPlugin()->getModuleSettings());
		$user = new User();
		$form->bind($user);
		$request = $this->getRequest();
		
		if($request->isPost()) {
			$form->setData($request->getPost());

			if($form->isValid()) {
				$userExist = $this->getUserModel()->checkBy(array(
					'email' => $user->getEmail(),
				));
				
				if(!$userExist) {
					$this->getUserModel()->saveUser($user);
				
					if($this->userModuleSettingsPlugin()->getLoginAfterRegistration()) {
						$request->setPost(new \Zend\Stdlib\Parameters(array(
							'user' => $user,
						)));
						return $this->forward()->dispatch('User\Controller\User', array('action' => 'authenticate'));
					}
					
					return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getLoginRoute());
				}
				
				$form->setMessages(array(
					'user' => array(
						'email' => array(
							'dbUnique' => 'This email is already in use',
						),
					),
				));
			}
		}

		return array(
         	'form' => $form,
			'enableRegistration' => $registrationEnable,
		);
	}
	
	public function changePasswordAction() {
		if(!$this->userAuthenticationPlugin()->hasIdentity()) {
			return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getLoginRoute());
        }
        $identity = $this->userAuthenticationPlugin()->getIdentity();
        $form = new \User\Form\ChangePasswordForm();
		$user = new User();
		$user->setId($identity->user_id);
		$form->bind($user);
		$request = $this->getRequest();
		
		if($request->isPost()) {
			$data = $request->getPost();
			$form->setData($data);

			if($form->isValid()) {
				$currentPassword = $this->getUserModel()->checkBy(array(
					'user_id' => $user->getId(),
					'password' => $user->getPassword(),
				));
				
				if($currentPassword) {
					$user->setPassword($data->user['newPassword']);
					$this->getUserModel()->changePassword($user);
					
					$this->flashmessenger()->addSuccessMessage("The update was successful!");
					return $this->redirect()->toRoute('user/changepassword');
				}
				
				$form->setMessages(array(
					'user' => array(
						'password' => array(
							'notSame' => 'The current password are incorrect',
						),
					),
				));
			}
		}
		
		return array(
         	'form' => $form
		);
	}
	
	public function profileAction() {
		if(!$this->userAuthenticationPlugin()->hasIdentity()) {
			return $this->redirect()->toRoute($this->userModuleSettingsPlugin()->getLoginRoute());
        }
        
        $identity = $this->userAuthenticationPlugin()->getIdentity();
		$form = new \User\Form\ProfileForm();
		$user = $this->getUserModel()->getUser($identity->user_id);
		$addresses = $form->get('user')
			 			  ->get('addresses');
			 			  
		foreach ($addresses as $address) {
			$address->get('countryId')
					->setValueOptions($this->getCountryModel()->fetchSelectOptions());
		}
		$form->bind($user);
		$request = $this->getRequest();
		
		if($request->isPost()) {
			$form->setData($request->getPost());

			if($form->isValid()) {
				var_dump($user);
				exit();
				$this->getUserModel()->saveUser($user);
			}
		}

		return array(
         	'form' => $form,
		);
	}
}